package tgc.edu.ljc.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.ljc.custom.AjaxResult;
import tgc.edu.ljc.custom.CommonController;
import tgc.edu.ljc.entity.SysDept;
import tgc.edu.ljc.entity.SysRole;
import tgc.edu.ljc.entity.SysUser;
import tgc.edu.ljc.security.UserUtils;
import tgc.edu.ljc.service.SysDeptService;
import tgc.edu.ljc.web.form.SysDeptForm;

@Controller
@RequestMapping(value = "/dept")
public class SysDeptController extends CommonController<SysDept, Integer, SysDeptForm> {

	@Autowired
	private SysDeptService sysdeptService;

	@Override
	public void edit(SysDeptForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		SysDept model = new SysDept();
		Integer id = form.getId();
		Integer parentId = form.getParentId(); // 父级id
		if (id != null) {
			model = sysdeptService.findById(id);
			parentId = model.getParentId();
		}
		if (parentId != null) { // 父级id
			SysDept parent = sysdeptService.findById(parentId);
			model.setParent(parent);
		}
		map.put("model", model);
	}

	@Override
	public Object save(SysDeptForm form) {
		try {
			SysDept model = new SysDept();
			Integer id = form.getId();
			if (id != null) {
				model = sysdeptService.findById(id);
			}
			// 父级菜单id
			Integer parentId = form.getParentId();
			if (parentId == null) {
				model.setParent(null);
			} else {
				model.setParent(new SysDept(parentId));
			}
			BeanUtils.copyProperties(form, model, "id", "parent");
			sysdeptService.save(model);
			return new AjaxResult("数据保存成功！");
		} catch (Exception e) {
			return new AjaxResult(false, "数据保存失败");
		}
	}

	/***
	 * 树形加载
	 * 
	 * @return
	 */
	@RequestMapping(value = "/treedata")
	@ResponseBody
	public Object treedata(Integer id) {
		Sort sort = Sort.by("idx1");
		Specification<SysDept> spec = buildSpec1(id);
		List<SysDept> list = sysdeptService.findAll(spec, sort);
		return buildTree(list, id);

	}

	private Object buildTree(List<SysDept> list, Integer id) {
		List<HashMap<String, Object>> result = new ArrayList<>();
		for (SysDept dept : list) {
			if (dept.getId() != id) {
				HashMap<String, Object> node = new HashMap<>();
				node.put("id", dept.getId());
				node.put("text", dept.getName());
				node.put("pid", dept.getParentId());
				node.put("nodes", buildTree(dept.getChildren(), id));
				result.add(node);
			}
		}
		return result;
	}

	public Specification<SysDept> buildSpec1(Integer id) {
		Specification<SysDept> specification = new Specification<SysDept>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<SysDept> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				Predicate parent;
				if (id != null) {
					parent = cb.equal(root.get("parent").get("id"), id);
				} else {
					parent = cb.isNull(root.get("parent"));
				}
				rules.add(parent);
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;
	}
	

}
